<?php

class SearchoneController extends Zend_Controller_Action {

    private $_root;
    private $_rssIndexDoc;
    private $_htmlIndexDoc;
    private $_feedButnerDoc;
    private $_newIndexDoc;

    public function init() {
        $this->_helper->layout->setLayout("search");
//        $this->_root = "/app/www/data";
        $this->_root = "/var/www/project-tracker/public/data";
        $this->_rssIndexDoc = $this->_root.'/search_one_index';
        $this->_htmlIndexDoc = $this->_root.'/html_index';
        $this->_feedButnerDoc = $this->_root.'/feedburner_index';
        $this->_newIndexDoc = $this->_root."/newIndex";
    }

    public function indexAction() {
        $form = new Application_Form_Searchone();
        $this->view->form = $form;        
    }

    public function createindexAction() {
        //create index
        $index = new Zend_Search_Lucene($this->_rssIndexDoc, true);

        $feeds = array(
//            'http://project-tracker-local.com/rss',
            // 'http://feeds.feedburner.com/FedoraCore?fmt=xml',
            'http://feeds.feedburner.com/ZendDeveloperZone',
                //   'http://www.planet-php.net/rss/',
                //   'http://www.sitepoint.com/blogs/category/php/feed/',
        );

        //grab each feed
        foreach ($feeds as $feed) {
            $channel = Zend_Feed::import($feed);
            echo "<b>" . $channel->title() . "</b><br>";
            //index each item
            foreach ($channel->items as $item) {

                if ($item->link() && $item->title() && $item->description()) {
                    $doc = new Zend_Search_Lucene_Document();
                    $doc->addField(Zend_Search_Lucene_Field::keyword('category', $this->sanitize(strtolower("Project"))));
                    $doc->addField(Zend_Search_Lucene_Field::keyword('link', $this->sanitize($item->link())));
                    $doc->addField(Zend_Search_Lucene_Field::text('title', $this->sanitize($item->title())));
                    $doc->addField(Zend_Search_Lucene_Field::text('contents', $this->sanitize($item->description())));
//                    if (isset($item->category())) {                        
//                        $cats = $item->category();
//                        foreach ($cats as $cat) {
//                             $doc->addField(Zend_Search_Lucene_Field::text('category', $this->sanitize($cat->nodeValue)));
//                        }
//                    }                                      
                    echo "<br><br>Adding: " . $item->title() . "<br><hr>";
                    $index->addDocument($doc);
                }
            }
        }
        $index->commit();
        echo $index->count() . " Document(s) indexed. <br>";
    }

    public function sanitize($input) {
        return htmlentities(strip_tags($input));
    }

    public function searchindexAction() {
        $form = new Application_Form_Searchone();
        $this->view->form = $form;

        if ($this->getRequest()->isPost()) {
            if ($form->isValid($this->getRequest()->getPost())) {
                $values = $form->getValues();
                $from = $values['from'];
                $this->view->from = $from;
//                $indexForSearch = $this->getIndexForSearch($from);
                $indexForSearch = $this->_newIndexDoc;


                switch ($from) {
                    case 'rss':
                        $index = new Zend_Search_Lucene($indexForSearch);
                        break;
                    case 'html':
                        $index = Zend_Search_Lucene::open($indexForSearch);
                        break;
                    default:
                        break;
                }
                $query = $this->sanitize(strtolower($values['searchString']));
                $hits = $index->find($query);
                $this->view->query = $query;
                $this->view->hits = $hits;
            }
        }
    }

    public function getIndexForSearch($selectOption) {
        $indexPath = '';
        switch ($selectOption) {
            case 'rss':
                $indexPath = $this->_rssIndexDoc;
                break;
            case 'html':
                $indexPath = $this->_htmlIndexDoc;
                break;
            default:
                break;
        }
        return $indexPath;
    }

    public function htmlindexcreateAction() {
        $index = new Zend_Search_Lucene($this->_htmlIndexDoc, true);
        $linksArray = array(
            array(
                'link' => 'http://www.google.com',
                'category' => array('search engine', 'internet'),
            ),
//            array(
//                'link' => "http://mammca.gtu.ac.in/",
//                'category1' => 'GTU',
//                'category2' => 'Degree Engineering College University',
//            ),
//            array(
//                'link' =>'http://gtuplacement.edu.in/',
//                'category'=>'GTU',
//                'category'=>'GTU placement',
//            ),
//            array(
//                'link'=>'http://where2service.com',
//                'category1'=>'where 2 service',
//                'category2'=>'Client',
//            ),
//            array(
//                'link' => 'http://feeds,feedburner.com/FedoraCore',
//                'category1' => 'Blog',
//                'category2' => 'Fedora cores'
//            ),
        );


        foreach ($linksArray as $mainLink) {
            $linkA = $mainLink['link'];
            $category1 = $mainLink['category1'];
            $category2 = $mainLink['category2'];
            $htmlDoc = $this->generateDocForHtmlLink($linkA, $category1, $category2);
            $index->addDocument($htmlDoc);
            $allLinks = $htmlDoc->getLinks();
            echo 'size of ' . sizeof($allLinks);
            foreach ($allLinks as $link) {
                echo '<br>' . $link;
                $htmlDoc2 = $this->generateDocForHtmlLink($link, $category1, $category2);
                $index->addDocument($htmlDoc2);
            }
//                    foreach ($allLinks as $link) {
//                        $htmlDoc2 = $this->generateDocForHtmlLink($link, $category1, $category2);
//                        $index->addDocument($htmlDoc2);
//                    }
        }
        $index->commit();
        $index->optimize();
        echo '<br>' . $index->count() . " document(s) added.";
    }

    public function getExtension($link) {
        $isFileExists = file_exists($link);
        $path_info = pathinfo($link);
        $extension = 'any';
        if ($isFileExists) {
            $extension = $path_info['extension'];
        }
        return $extension;
    }

    public function generateDocForHtmlLink($link, $category1, $category2) {
        $htmlDoc = Zend_Search_Lucene_Document_Html::loadHTMLFile($link);
        $htmlDoc->addField(Zend_Search_Lucene_Field::keyword('category1', $this->sanitize(strtolower($category1))));
        $htmlDoc->addField(Zend_Search_Lucene_Field::keyword('category2', $this->sanitize(strtolower($category2))));
        $htmlDoc->addField(Zend_Search_Lucene_Field::keyword('link', $link));
//                $content = substr(strip_tags($htmlDoc->getHtmlBody()), 0, 300);
//                $htmlDoc->addField(Zend_Search_Lucene_Field::text('content', $content . '...'));
        return $htmlDoc;
    }

    public function readfeedburnerfeedAction() {
        $location = $this->_newIndexDoc;
        $feederUrls = array(
            array(
                'link' => "http://feeds.feedburner.com/FedoraCore",
                'category' => array('Blog', 'Fedora Core', 'Atom'),
            ),
//            array(
//                'link' => "http://project-tracker-local.com/rss",
//                'category' => array('Project Tracker', 'Project Geannie', 'Personal', 'RSS'),
//            ),
            array(
                'link' => "http://www.planet-php.net/rss/",
                'category' => array('Planet PHP', 'RSS'),
            ),
        );
        $feeder = new Search_Feeder();
        $feeder->generateNewSearchIndex($location, $feederUrls);
    }

    public function test() {
        $feed = "http://feeds.feedburner.com/FedoraCore";
//        $rss = 'http://feeds.feedburner.com/ZendDeveloperZone';
//        $rss = "http://project-tracker-local.com/rss";
        $rss = "http://www.planet-php.net/rss/";
        $isAtom = false;
        $xml = simplexml_load_file($rss);
        if ($xml->getName() == "feed") {
            $isAtom = true;
        }
        $channel = Zend_Feed::import($rss);
        echo '<pre>';
        echo "Metadata:<br>";
        echo 'Channel  Title: ' . $channel->title() . '<br>';
        echo 'Link: ' . $channel->link() . '<br>';
        echo 'Desc: ' . $channel->description() . '<br>';
        echo 'Pub Date: ' . $channel->pubDate() . '<br>';
        echo 'Generator: ' . $channel->generator() . '<br>';
        echo 'Author: ' . $channel->author() . '<br>';
        echo 'Docs: ' . $channel->docs() . '<br>';
        echo 'Total: <b>' . $channel->count() . '</b><br>';
        echo '</pre>';
        if (!$isAtom) {
            foreach ($channel as $item) {
                echo '<br><b>' . $item->title() . '</b><br>';
                echo 'Link: ' . $item->link() . '<br>';
                echo 'Author: ' . $item->author() . '<br>';
                echo 'Category: ' . $item->category() . '<br>';
                echo 'Desc: ' . $this->sanitize($item->description());

                echo '<hr>';
            }
        } else {
            foreach ($channel as $entry) {
                echo '<br><b>' . $entry->title() . '</b><br>';
                echo 'Link: ' . $entry->link('alternate') . '<br>';
                echo '<br>Summary: ' . $this->sanitize($entry->content()) . '<br>';
                echo '<hr>';
            }
        }
    }

}

